﻿using UnityEngine;

namespace CGF
{
    public class AndroidHelper
    {
        public static int GetAndroidSDKVersion()
        {
            try
            {
                using (AndroidJavaClass version = new AndroidJavaClass("android.os.Build$VERSION"))
                {
                    return version.GetStatic<int>("SDK_INT");
                }
            }
            catch (System.Exception e)
            {
                Debug.LogError("获取Android SDK版本失败: " + e.Message);
                return 0;
            }
        }
        
        private static AndroidJavaObject _currActivity;
        public static AndroidJavaObject CurrActivity
        {
            get
            {
#if UNITY_ANDROID && !UNITY_EDITOR
                if (_currActivity == null)
                {
                    AndroidJavaClass javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
                    _currActivity = javaClass.GetStatic<AndroidJavaObject>("currentActivity");
                }
#endif
                return _currActivity;
            }
        }

        /// <summary>
        /// 调用Java(Android)层MainActivity类的函数
        /// </summary>
        public static void CallMainActivityFunction(string functionName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            CurrActivity.Call(functionName, args);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层MainActivity类的函数，有返回值
        /// </summary>
        public static T CallMainActivityFunction<T>(string functionName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            if(args == null)
            {
                return CurrActivity.Call<T>(functionName);
            }
            else
            {
                return CurrActivity.Call<T>(functionName, args);
            }
#else
            return default(T);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层的静态函数，无返回值
        /// </summary>
        public static void CallStaticFunction(string classPath, string methodName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass jc = new AndroidJavaClass(classPath);
            jc.CallStatic(methodName, args);
#endif
        }

        /// <summary>
        /// 调用Java(Android)层的静态函数，有返回值
        /// </summary>
        public static T CallStaticFunction<T>(string classPath, string methodName, params object[] args)
        {
#if UNITY_ANDROID && !UNITY_EDITOR
            AndroidJavaClass jc = new AndroidJavaClass(classPath);
            return jc.CallStatic<T>(methodName, args);
#else
            return default(T);
#endif
        }
    }
}